package com.heima.schedule.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.RedisCacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;

/**
 * @Author: JW
 * @Description: TODO
 * @DateTime: 2022-02-16 22:20
 **/
@Service
@Transactional
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private RedisCacheService redisCacheService;

    /***
     * @Author: JW
     * @Description: TODO 添加任务
     * @Date: 22:18 2022-02-16
     * @Param: [task] 任务对象
     * @return: long 任务id
     * @param task
     */
    @Override
    public long addTask(Task task) {

        boolean flag = addTaskToDB(task);

        if (flag){
            //添加到redis中
            addTaskToRedis(task);
        }

        return task.getTaskId();
    }

    /**
     * @param taskId
     * @Author: JW
     * @Description: TODO 取消任务
     * @Date: 23:05 2022-02-16
     * @Param: [taskId] 任务id
     * @return: boolean 结果
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = false;

        //删除任务，更新日志
        Task task = removeTaskDB(taskId,ScheduleConstants.CANCELLED);

        //删除redis的数据
        if(task != null){
            removeTaskRedis(task);
            flag = true;
        }
        return flag;
    }

    /**
     * @param type
     * @param priority
     * @Author: JW
     * @Description: TODO 消费任务
     * @Date: 23:19 2022-02-16
     * @Param: [type, priority]
     * @return: com.heima.model.schedule.dtos.Task 返回任务
     */
    @Override
    public Task pull(int type, int priority) {

        Task task = null;

        String key = type + "_" + priority;

        //移除redis中的数据 并拿到task
        String taskJson = redisCacheService.lRightPop(ScheduleConstants.TOPIC + key);

        if (StringUtils.isNotBlank(taskJson)) {

            //解析task
            task = JSON.parseObject(taskJson, Task.class);
            //更新数据库信息
            removeTaskDB(task.getTaskId(), ScheduleConstants.EXECUTED);
        }

        return task;
    }

    /**
     * @Author: JW
     * @Description:  TODO 删除redis中任务
     * @Date: 23:16 2022-02-16
     * @Param: [task]
     * @return: void
    **/
    private void removeTaskRedis(Task task) {

        String key = task.getTaskType()+"_"+task.getPriority();

        if(task.getExecuteTime()<=System.currentTimeMillis()){
            redisCacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));
        }else {
            redisCacheService.zRemove(ScheduleConstants.FUTURE+key, JSON.toJSONString(task));
        }
    }

    /**
     * @Author: JW
     * @Description:  TODO 删除任务 更新日志
     * @Date: 23:10 2022-02-16
     * @Param: [taskId]
     * @return: com.heima.model.schedule.dtos.Task
    **/
    private Task removeTaskDB(long taskId,int status) {

        //删除任务
        taskinfoMapper.deleteById(taskId);

        //更新日志表
        TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
        taskinfoLogs.setStatus(status);
        taskinfoLogsMapper.updateById(taskinfoLogs);

        //返回删除任务
        Task task = new Task();
        BeanUtils.copyProperties(taskinfoLogs,task);
        task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());

        return task;
    }

    /**
     * @Author: JW
     * @Description:  TODO 保存任务到redis中
     * @Date: 22:48 2022-02-16
     * @Param: [task]
     * @return: void
    **/
    private void addTaskToRedis(Task task) {

        String key = task.getTaskType() + "_" + task.getPriority();

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        long futureTime = calendar.getTimeInMillis();

        //当小于当前时间时，应该进入消费任务
        if (task.getExecuteTime() <= System.currentTimeMillis()){

            redisCacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        }else if (task.getExecuteTime() <= futureTime){

            //未来五分钟内进入未来队列
            redisCacheService.zAdd(ScheduleConstants.FUTURE + key,
                    JSON.toJSONString(task),task.getExecuteTime());
        }
    }

    /**
     * @Author: JW
     * @Description:  TODO 保存数据到MySQL中 更新日志
     * @Date: 22:27 2022-02-16
     * @Param: [task]
     * @return: boolean
    **/
    private boolean addTaskToDB(Task task) {

        boolean flag = false;

        try {
            //保存任务信息表中
            Taskinfo taskinfo = new Taskinfo();

            //补全参数
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));

            taskinfoMapper.insert(taskinfo);

            //保存到日志表
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            //补全参数
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);

            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }
}
